package com.wealth.lottery.web.controller;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wealth.lottery.entity.LotteryActivity;
import com.wealth.lottery.entity.LotteryNumber;
import com.wealth.lottery.entity.LotteryPrize;
import com.wealth.lottery.entity.LotteryRecord;
import com.wealth.lottery.enums.LotteryActivityRecodeEnums;
import com.wealth.lottery.enums.LotteryActivityStatusEnums;
import com.wealth.lottery.service.ILotteryActivityService;
import com.wealth.lottery.service.ILotteryNumberService;
import com.wealth.lottery.service.ILotteryPrizeService;
import com.wealth.lottery.service.ILotteryRecordService;
import com.wealth.lottery.util.RandomLotteryLuckNum;
import com.wealth.system.web.controller.BaseController;

import iaas.utils.ResultObject;

@Controller
@RequestMapping(value="/manage/lottery")
public class LotteryController extends BaseController{

	Logger logger = Logger.getLogger(LotteryController.class);
	@Autowired
	private ILotteryActivityService activityService;
	@Autowired
	private ILotteryPrizeService iLotteryPrizeService;
	@Autowired
	private ILotteryNumberService iLotteryNumberService;
	@Autowired
	private ILotteryRecordService iLotteryRecordService;
 	private final ReentrantLock lock = new ReentrantLock();
 	
 	
 	
	@RequestMapping(value="/index/{lotteryid}")
	public String toPage(@PathVariable Long lotteryid,Model model){
		try {
//			int one   = lotteryid.indexOf("activity@");
//			String sone = lotteryid.substring(one,lotteryid.length());
//			int two = sone.indexOf("@");
//			String stwo = sone.substring(two+1, sone.length());
//			LotteryActivity activity = activityService.get(Long.valueOf(stwo));
			LotteryActivity activity = activityService.get(lotteryid);
			List<LotteryPrize> prizeList = activity.getPrizeList();
			int total = 0;
			LotteryNumber number = iLotteryNumberService.getByMember(memberid, Long.valueOf(lotteryid));
			if(number!=null){
				total = number.getTotal();
			}
			model.addAttribute("total", total);
			model.addAttribute("activity", activity);
			model.addAttribute("prizeList", prizeList);
			return "lottery/newLottery";
		} catch (Exception e) {
			logger.error(e);
			return "system/500";
		}
	}
	
	
	@RequestMapping(value="/start/{corpid}")
	@ResponseBody
	public ResultObject  startActivity(@PathVariable Long corpid, HttpServletRequest request){
		try {
			Long activityid=Long.valueOf(request.getParameter("activityid"));
			LotteryActivity activity = activityService.get(activityid);
			if(activity.getStatus()==LotteryActivityStatusEnums.DELETE.getValue()||activity.getStatus()==LotteryActivityStatusEnums.STOP.getValue()){
				return new ResultObject("999", "没有抽奖机会了", null);
			}
			//间隔
			DateTime start = new DateTime(activity.getStartTime());
			DateTime end = new DateTime(activity.getEndTime());
			Interval i = new Interval(start, end);
			if(!i.contains(new DateTime())){
				return new ResultObject("999", "已过期", "");
			}

			/**减少用户的抽奖次数*/
			LotteryNumber number = iLotteryNumberService.getByMember(memberid, Long.valueOf(activityid));
			if(number!=null){
				if(number.getTotal()>=1){
					number.setTotal(number.getTotal()-1);
					iLotteryNumberService.save(number);
					return getactivityprize(Long.valueOf(activityid), corpid);
				}else{
					return new ResultObject("100", "没有抽奖机会了", null);
				}
			}else{
				return new ResultObject("100", "没有抽奖机会了", null);
			}
		} catch (Exception e) {
			logger.error(e);
			return  new ResultObject("500", "抽奖失败",null);
		}
		
	}
	@RequestMapping(value="/vatotal",method=RequestMethod.POST)
	@ResponseBody
	public ResultObject  viActivity(HttpServletRequest request){
		try {
			String money=	request.getParameter("total");
			Double d_money = null;
			if(StringUtils.isBlank(money)){
				d_money = 0D;
			}else{
				d_money = Double.valueOf(money);
			}

			return activityService.getByScoreGt(d_money, 1L,memberid);

		} catch (Exception e) {
			logger.error(e);
			return  new ResultObject("500", "抽奖失败",null);
		}
		
	}
	private void updatePrizeLuckNum(Long corpid, Long activityid, LotteryPrize prize, int lucknum) throws Exception {
		/** 1.更新奖品的中奖数 */
		prize.setTotal(prize.getTotal() + 1);
		/** 2.更新奖品的库存 */
		prize.setStock(prize.getStock() - 1);
		/** 3.记录中奖命中次数 */
		String orderlucknum = prize.getOrderlucknum();
		StringBuffer sb = new StringBuffer();
		prize.setOrderlucknum(sb.append(orderlucknum).append(",").append(String.valueOf(lucknum)).toString());
		if (prize.getStock() > 0) {
			/** 1.查询已经中奖和已经生成的中奖号码,新生成的号码不应该与这些号码相同 */
			List<Integer> orderlucknumList = new LinkedList<Integer>(); /** 所有中奖号码的集合 */
			List<LotteryPrize> prizeList = iLotteryPrizeService.getPrizeByActivity(activityid, corpid);
			/** 把所有的中奖号码拼成一个字符串 */
			if (prizeList.size() > 0) {
				StringBuffer ordernum = new StringBuffer();
				for (int i = 0; i < prizeList.size(); i++) {
						ordernum.append(prizeList.get(i).getOrderlucknum()).append(",")
								.append(prizeList.get(i).getLucknum());
				}
				/** 得到所有的中奖号码字符串 */
				String s_ordernum = ordernum.toString();
				String[] ordernumList = s_ordernum.split(",");
				/** 转换成数字存到所有中奖号码的集合 */
				for (int i = 0; i < ordernumList.length; i++) {
					orderlucknumList.add(Integer.valueOf(ordernumList[i]));
				}
			}
			/** 2.更新中奖次数 */
			prize.setLucknumber(prize.getLucknumber() + 1);
			/** 3.更新该奖品中奖下一次的命中次数 */
			int u_lucknum = RandomLotteryLuckNum.randomLuckNum(prize.getLucknumber(), prize.getOrdernum(),
					orderlucknumList, prize.getProbability());
			prize.setLucknum(u_lucknum);
		} else {
			/** 如果该商品没有了库存，则清空该奖品的中奖号码。保证该奖品不会被再次抽中，将号码设为0 */
			prize.setLucknum(0);
		}
		/** 保存奖品信息 */
		iLotteryPrizeService.save(prize);
	}
	
    /** 抽奖方法(绝对概率) lihang 2016-07-26 */
	@SuppressWarnings("finally")
	public ResultObject getactivityprize(Long activityid,Long corpid) throws Exception {
		ResultObject result = null;
		/** 标识是否中奖 */
		int status = -1;
		/** 中奖的奖品id */
		Long prizeid = null;
		/**中奖纪录*/
		LotteryRecord record=null;
		LotteryPrize prize=null;
		try {
			lock.lock();
			//Member member = corpService.getMemberByOpenidAndCorpId(openid, corpid);
			/** 插入抽奖记录 */
			record= iLotteryRecordService.addMemberRecode(status, corpid, activityid, prizeid,
					memberid);
			/** 1.统计共有多少人抽奖 */
			int lucknum = iLotteryRecordService.getLotteryRecodeNum(activityid);
			/** 3.去匹配是否有奖品被抽中，并生成抽奖纪录 */
			prize = iLotteryPrizeService.getluckPrize(activityid, lucknum, corpid);
			/** 条件1 没有中奖品 */
			if (prize == null) {
				status = LotteryActivityRecodeEnums.NO.getValue();
				result = new ResultObject("300", "没有中奖", null);
				/** 修改记录 */
				record.setStatus(status);
				record.setPrize(prize);
				iLotteryRecordService.save(record);
				return result;
			}
			/** 更新中奖奖品的信息 star */
			/** 开始中奖 */
			/** 设置状态为中奖 */
			status = LotteryActivityRecodeEnums.YES.getValue();
			/** 更新奖品的中奖命中次数 star */
			updatePrizeLuckNum(corpid, activityid, prize, lucknum);
			//vo.setLotteryPrize(prize);
			result = new ResultObject("500", "用户中奖", prize);
			/** 根据不同的奖品开始发奖品 */
			/** 如果是红包，直接发奖 */
		} catch (Exception e) {
			logger.error(e);
			status = LotteryActivityRecodeEnums.NO.getValue();
			prize=null;
			result = new ResultObject("400", "抽奖错误", null);
		} finally {
			if (lock.isLocked()) {
				lock.unlock();
			}
			/** 修改记录 */
			if(result.getCode().equals("300")){
				prize=null;
			}
			record.setStatus(status);
			record.setPrize(prize);
			iLotteryRecordService.save(record);
			return result;
		}
	}
	
	/*public static void main(String[] args) {
		String dd  = "ddsdasddasdasdasdasdadasdadindex@4";
		int a =  dd.indexOf("index@");
		String c =  dd.substring(a, dd.length());
		String e = c.substring(c.indexOf("@")+1, c.length());
		System.out.println(e);
	}*/
	/* public static void generateKey() {  
	        try {  
	            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");  
	            kpg.initialize(1024);  
	            KeyPair kp = kpg.genKeyPair();  
	            PublicKey pbkey = kp.getPublic();  
	            PrivateKey prkey = kp.getPrivate();  
	            // 保存公钥  
	            FileOutputStream f1 = new FileOutputStream("pubkey.dat");  
	            ObjectOutputStream b1 = new ObjectOutputStream(f1);  
	            b1.writeObject(pbkey);  
	            // 保存私钥  
	            FileOutputStream f2 = new FileOutputStream("privatekey.dat");  
	            ObjectOutputStream b2 = new ObjectOutputStream(f2);  
	            b2.writeObject(prkey);  
	        } catch (Exception e) {  
	        }  
	    }  
	    public static void encrypt() throws Exception {  
	        String s = "1";  
	        // 获取公钥及参数e,n  
	        FileInputStream f = new FileInputStream("pubkey.dat");  
	        ObjectInputStream b = new ObjectInputStream(f);  
	        RSAPublicKey pbk = (RSAPublicKey) b.readObject();  
	        BigInteger e = pbk.getPublicExponent();  
	        BigInteger n = pbk.getModulus();  
	        System.out.println("e= " + e);  
	        System.out.println("n= " + n);  
	        // 获取明文m  
	        byte ptext[] = s.getBytes("UTF-8");  
	        BigInteger m = new BigInteger(ptext);  
	        // 计算密文c  
	        BigInteger c = m.modPow(e, n);  
	        System.out.println("c= " + c);  
	        // 保存密文  
	        String cs = c.toString();  
	        BufferedWriter out =  
	            new BufferedWriter(  
	                new OutputStreamWriter(new FileOutputStream("encrypt.dat")));  
	        out.write(cs, 0, cs.length());  
	        out.close();  
	    }  
	    public static void decrypt() throws Exception {  
	        // 读取密文  
	        BufferedReader in =  
	            new BufferedReader(  
	                new InputStreamReader(new FileInputStream("encrypt.dat")));  
	        String ctext = in.readLine();  
	        BigInteger c = new BigInteger(ctext);  
	        // 读取私钥  
	        FileInputStream f = new FileInputStream("privatekey.dat");  
	        ObjectInputStream b = new ObjectInputStream(f);  
	        RSAPrivateKey prk = (RSAPrivateKey) b.readObject();  
	        BigInteger d = prk.getPrivateExponent();  
	        // 获取私钥参数及解密  
	        BigInteger n = prk.getModulus();  
	        System.out.println("d= " + d);  
	        System.out.println("n= " + n);  
	        BigInteger m = c.modPow(d, n);  
	        // 显示解密结果  
	        System.out.println("m= " + m);  
	        byte[] mt = m.toByteArray();  
	        System.out.println("PlainText is ");  
	        for (int i = 0; i < mt.length; i++) {  
	            System.out.print((char) mt[i]);  
	        }  
	    }  
	    public static void main(String args[]) {  
	        try {  
	            //generateKey();  
	            //encrypt();  
	            decrypt();  
	        } catch (Exception e) {  
	            System.out.println(e.toString());  
	        }  
	    }  */
}
